package com.controller.aspect;

import com.alibaba.fastjson.JSON;
import com.business.bean.SysLog;
import com.business.service.SysLogService;
import com.controller.annotation.LogMenthodName;
import com.controller.config.shiro.ShiroConfiguration;
import com.google.common.collect.Maps;
import com.mysql.jdbc.jdbc2.optional.SuspendableXAConnection;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.web.util.WebUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.Enumeration;
import java.util.Map;

/**
 * @author 张子艺
 * @packge com.controller.aspect
 * @data 2019-01-09 14:03
 * @project Currency
 */
@Aspect
@Component
public class WebLogAcpect {
    private Logger logger = LoggerFactory.getLogger(WebLogAcpect.class);
    //计算时间
    ThreadLocal<Long> startTime = new ThreadLocal<>();
    private SysLog sysLog;
    @Autowired
    SysLogService sysLogService;

    /**
     * 定义切入点，切入点为com.controller下的所有函数
     */
    @Pointcut("execution(public * com.controller.admin.*.*(..))")
    public void webLog() {
    }

    /**
     * 前置通知：在连接点之前执行的通知
     *
     * @param joinPoint
     * @throws Throwable
     */
    @Before("webLog()")
    public void doBefore(JoinPoint joinPoint) throws Throwable {
        startTime.set(System.currentTimeMillis());
        // 接收到请求，记录请求内容
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        Signature signature = joinPoint.getSignature();
        MethodSignature methodSignature = (MethodSignature) signature;
        Method method = methodSignature.getMethod();
        Object params[] = joinPoint.getArgs();
        //自定义注解的方法操作别名
        LogMenthodName logMenthodName = method.getAnnotation(LogMenthodName.class);
        //判断方法是否存在这个注解
        if (method.isAnnotationPresent(LogMenthodName.class)) {
            sysLog = new SysLog();
            sysLog.setRequestUrl(request.getRequestURL().toString());
            sysLog.setRequestWay(request.getMethod());
            sysLog.setCreateTime(System.currentTimeMillis());
            sysLog.setIp(request.getRemoteAddr());
            sysLog.setMethodUrl(signature.getDeclaringTypeName() + "." + signature.getName());
            sysLog.setMethodName(logMenthodName.name());
            if (params.length == 0) {
                sysLog.setRequestParam("无参数");
            } else {
                sysLog.setRequestParam(Arrays.toString(params));
            }
        }else{
            //设置日期格式
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            // 记录下请求内容
            logger.debug("------------------------------------------------------------------------------------------------");
            logger.debug("请求地址: " + request.getRequestURL().toString());
            logger.debug("请求方式: " + request.getMethod());
            logger.debug("请求时间: " + df.format(new Date()));
            logger.debug("IP : " + request.getRemoteAddr());
            logger.debug("方法地址 : " + signature.getDeclaringTypeName() + "." + signature.getName());
            if (logMenthodName == null) {
                logger.debug("方法别名 : 未知");
            } else {
                logger.debug("方法别名 : " + logMenthodName.name());
            }
            if (params.length == 0) {
                logger.debug("请求参数 : 无参");
            } else {
                logger.debug("请求参数 : " + Arrays.toString(params));
            }
        }
    }

    @AfterReturning(returning = "ret", pointcut = "webLog()")
    public void doAfterReturning(JoinPoint joinPoint,Object ret) throws Throwable {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        Signature signature = joinPoint.getSignature();
        MethodSignature methodSignature = (MethodSignature) signature;
        Method method = methodSignature.getMethod();
        LogMenthodName logMenthodName = method.getAnnotation(LogMenthodName.class);
        String time = (System.currentTimeMillis() - startTime.get()) + "ms";
        if(method.isAnnotationPresent(LogMenthodName.class)){
            sysLog.setReturnParam(ret.toString());
            sysLog.setTime(time);
            sysLogService.insert(sysLog);
        }
        // 处理完请求，返回内容
        logger.debug("返回内容: " + ret);
        logger.debug("耗时 : " + time);


    }
}
